import Decoractor from './Decoractor';
import ViewMgr from '../manager/ViewMgr';

export class BaseComponent extends cc.Component {
  public onLoad(): void {
    this.registerEvents();
  }

  protected registerEvents(): void {
    let eventMap = this.getEventMap();

    if (eventMap) {
      Object.keys(eventMap).forEach((key) => {
        for (let i: number = 0; i < eventMap[key].length; i++) {
          let methodName: string = eventMap[key][i];
          let callback = this[methodName];
          if (callback) {
            ViewMgr.ins.addEventListener(key, callback, this);
            //core.EventMgr.inst.addEventListener(key, callback, this);
          }
        }
      });
    }
  }

  protected getEventMap(): Object {
    let eventMap = null;
    let className = this['__proto__'].__classname__;
    if (className) {
      let obj = Decoractor.classEventMap[className];
      if (obj) {
        if (!eventMap) eventMap = {};
        (<any>Object).assign(eventMap, obj);
      }
    }
    return eventMap;
  }
}
